'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: response.py
* @Time: 2025/11/5
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass, field
from typing import Any, Union, Generator
from flask import jsonify, Response, stream_with_context
from pkg.response.http_code import HttpCode
from flask import Response as FlaskResponse

@dataclass
class Response:
    """基于Http接口响应 格式参数"""
    code:HttpCode = HttpCode.SUCCESS
    message:str=""
    data:Any = field(default=dict)


def json(data:Response = None):
    return jsonify(data), 200


def success_json(data:Any = None):
    return json(Response(code=HttpCode.SUCCESS, message="", data=data))


def fail_json(data:Any = None):
    return json(Response(code=HttpCode.FAIL, message="", data=data))


def validate_error_json(errors:dict):
    first_key = next(iter(errors))

    if first_key is not None:
        msg = errors.get(first_key)[0]
        return json(Response(code=HttpCode.VALIDATE_ERROR, message=msg, data=errors))
    else:
        return json(Response(code=HttpCode.VALIDATE_ERROR, message="", data=errors))


def message(code:HttpCode = None, msg:str=""):
    return json(Response(code=code, message=msg, data={}))


def success_message(msg:str=""):
    return message(code=HttpCode.SUCCESS, msg=msg)


def fail_message(msg:str=""):
    return message(code=HttpCode.FAIL, msg=msg)


def not_found_message(msg:str=""):
    return message(code=HttpCode.NOT_FOUND, msg=msg)


def unauthorized_message(msg:str=""):
    return message(code=HttpCode.UNAUTHORIZED, msg=msg)


def forbidden_message(msg:str=""):
    return message(code=HttpCode.FORBIDDEN, msg=msg)


def compact_generate_response(response:Union[Response, Generator])-> tuple[Response, int] | FlaskResponse:
    """统一合并处理，块输出和流式时间响应（SSE）"""
    #1、检测是否是 块输出
    if isinstance(response, Response):
        return json(response)
    else:
        def generate()->Generator:
            """构建generate 函数，流式数据冲response中获取"""
            yield from response
        return FlaskResponse(
            stream_with_context(generate()),
            status=200,
            mimetype='text/event-stream',
        )
